<?php

namespace App\Services;

use App\Exceptions\TokenRequestException;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\ClientException;

class KongOauthService
{
    /**
     * @param $userId
     * @param string $scope
     * @return mixed
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public static function getToken($userId, $scope='student')
    {
        if (is_array($scope)) {
            $scope = implode(' ', $scope);
        }
        try {
            $client = new Client();
            $oauthUrl = config('service.kong_oauth_url');
            $response = $client->request('POST', $oauthUrl, [
                'form_params' => [
                    'grant_type' => 'password',
                    'provision_key' => config('service.kong_oauth_provision_key'),
                    'client_id' => config('service.kong_oauth_client_id'),
                    'client_secret' => config('service.kong_oauth_client_secret'),
                    'scope' => $scope,
                    'authenticated_userid' => $userId
                ],
                'verify' => false
            ]);
            $result = json_decode($response->getBody(), true);
            return [
                'refreshToken' => $result['refresh_token'],
                'tokenType' => $result['token_type'],
                'accessToken' => $result['access_token'],
                'expiresIn' => $result['expires_in']
            ];
        } catch (ClientException $e) {
            throw new TokenRequestException($e->getMessage());
        }
    }

    /**
     * @param $token
     * @return mixed
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public static function refreshToken($token)
    {
        try {
            $client = new Client();
            $oauthUrl = config('service.kong_oauth_url');
            $response = $client->request('POST', $oauthUrl, [
                'form_params' => [
                    'grant_type' => 'refresh_token',
                    'client_id' => config('service.kong_oauth_client_id'),
                    'client_secret' => config('service.kong_oauth_client_secret'),
                    'refresh_token' => $token
                ],
                'verify' => false
            ]);
            $result = json_decode($response->getBody());
            return [
                'refreshToken' => $result['refresh_token'],
                'tokenType' => $result['token_type'],
                'accessToken' => $result['access_token'],
                'expiresIn' => $result['expires_in']
            ];
        } catch (ClientException $e) {
            throw new TokenRequestException($e->getMessage());
        }
    }
}